<template>
    <div class="ups" v-if="props.showtype=='card'">
        <div v-for="(item,index) in fileurls" :key="item" class="fileDiv">
            
            <el-image v-if="!item.progressFlag&&item.fileUrl && item.isImg" :src="item.fileUrl" :previewSrcList="[item.fileUrl]" fit="cover" class="avatar" />
            <!-- 如下 文件暂时不让预览 -->
            <!-- @click="PreviewFile(item.fileUrl)" -->
            <div v-if="!item.progressFlag&&item.fileUrl && !item.isImg" class="avatar-uploader-file hidden pointer flex-column-center">
                <span class="w100 pd5-row lineOne flex-center">{{item.name.substring(0,10)}}.{{ item.filrType }}</span>
            </div>
            <span class="up_del flex-row-center">
                <el-icon v-if="props.isDownload&&props.accept.includes('*')" class="down ml10" @click="download(item.fileUrl)" v-show="item.fileUrl"><svg width="32" height="32" viewBox="0 0 24 24"><path fill="currentColor" d="M19.35 10.04A7.49 7.49 0 0 0 12 4C9.11 4 6.6 5.64 5.35 8.04A5.994 5.994 0 0 0 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5c0-2.64-2.05-4.78-4.65-4.96M17 13l-5 5l-5-5h3V9h4v4z"/></svg></el-icon>
                <el-icon v-if="props.isEdit" v-show="item.fileUrl" class="del ml10" @click="del(index)"><DeleteFilled /></el-icon>
            </span>
            <div class="progress" v-show="item.progressFlag">
                <span><u :style="'width:'+item.loadProgress+'%'"></u></span>
                <i v-if="item.loadProgress>0">{{item.loadProgress}}%</i>
            </div>
        </div>
        <div class="upDiv" v-if="props.isEdit">
            <span class="avatar-uploader"></span>
            <input type="file" :accept="accept" multiple="multiple" @change="upfile" />
        </div>
    </div>
    <div class="lineups" v-else>
        <div class="lineupDiv">
            <div class="avatar-uploader">{{buttontext||'选择文件'}}</div>
            <input type="file" :accept="accept" multiple="multiple" @change="upfile" />
        </div>
        <div class="fileDivbox">
            <div v-for="(item,index) in fileurls" :key="item" class="fileDiv">
                <div v-if="item.fileUrl" class="avatar-uploader-file hidden pointer flex-column-center" @click="PreviewFile(item.fileUrl)">
                    <span class="w100 pd5-row lineOne flex-center">{{item.name.substring(0,8)}}.{{ item.filrType }}</span>
                </div>
                <span class="up_del" v-show="item.fileUrl" @click="del(index)"></span>
                <div class="progressbox" v-if="!item.fileUrl">
                    <span class="up_uploading">上传中...</span>
                    <span class="progress" v-show="item.progressFlag">
                        <span><u :style="'width:'+item.loadProgress"></u></span>
                        <i>{{item.loadProgress}}</i>
                    </span>
                </div>
            </div>
        </div>
    </div>
    <div class="pre-dialog" v-if="obj.PreviewObj.Visible" @click="obj.PreviewObj.Visible=false">
        <div class="close-icon" @click="obj.PreviewObj.Visible=false">
            <el-icon style="margin-top: 7px;" color="#fff">
                <Close />
            </el-icon>
        </div>
        <el-image v-if="['jpg','png','jpeg','gif'].includes(obj.PreviewObj.type)" class="h100" :src="obj.PreviewObj.fileURL" fit="cover" @click.stop="()=>{}" />
        <iframe v-else-if="['pdf'].includes(obj.PreviewObj.type)" class="w80 h100" :src="obj.PreviewObj.fileURL"></iframe>
        <div v-else class="w80 h100 w-bg flex-center mini-gray-size">
            <a class="nodata-a" download :href="obj.PreviewObj.fileURL">-- 不支持预览 点击下载 --</a>
        </div>
    </div>
</template>

<script setup>
import { ref,reactive,getCurrentInstance,toRefs,toRaw,computed, pushScopeId,watch,onMounted } from 'vue'
import { Close,DeleteFilled } from "@element-plus/icons-vue";
let { proxy } = getCurrentInstance()
const emit = defineEmits(['update:files']) //此处要完全对应，采用固定的update:prop属性
const imgTypes = ['jpg','jpeg','png','gif']
let isUpload = false //默认没上传过

const props = defineProps({
    accept: { type: Array, default: ['image/jpeg','image/png','image/gif'] }, //'application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    debug: { type: Boolean, default: false },
    files: { type: String, default: "", require: true },
    dir: { type: String, default: "" },
    maxlength: { type: Number, default: 0 }, //默认0，不限制
    maxsize: { type: Number, default: 1024 * 1024 * 5 }, //单位K，默认5120K，即5M
    maxwidth: { type: Number, default: 0 },
    maxheight: { type: Number, default: 0 },
    background: { type: String, default: "" },
    showtype: { type: String, default: "card" },//card line
    isEdit: { type: Boolean, default: true },
    isDownload: { type: Boolean, default: false },
    buttontext: { type: String, default: "选择文件" },
})

let obj = reactive({
    fileurls: [],
    old_files: null,
    PreviewObj: {
        Visible: false,
        type: '',
        fileURL: ''
    },
})

onMounted(()=>{
})

let init = val => {
    return val.split(",").filter(t => t!="").map(t => {
        let tmp = {
            id: Math.random(),
            name: t,
            progressFlag: false,
            loadProgress: "0%",
            fileUrl: "",
            isImg: props.accept.includes('*')?'':(t=="" ? "" : imgTypes.some(p => p === t.split('.').pop().toLowerCase())),
            filrType:  t.split('.')[1]
        }
        const isUpload = !(obj.old_files.includes(t))
        if (!isUpload && t != "")
            tmp.fileUrl = `${proxy.$setting.globalUrl.fileurl}/${props.dir}/${t}`
        if (isUpload && t != "")
            tmp.fileUrl = `${proxy.$setting.globalUrl.upload}/${t}`
        return tmp
    })
}

watch(
    () => props.files,
    (val) => {
        if(obj.old_files===null){
            obj.old_files = props.files||''
        }
        obj.fileurls = init(val)
    }
)

let del = i => {
    obj.fileurls.splice(i,1)
    const files = (Array.from(obj.fileurls,({name})=>name)).join(',')
    emit('update:files',files)
    proxy.useTrigger()
}
let upfile = async(e) => {
    if(obj.old_files===null){
        obj.old_files = ''
    }
    let files = []
    for(let i=0; i<e.srcElement.files.length; i++){
        files.push(e.srcElement.files[i])
    }
    let upresult = []
    for(let i=0; i<files.length; i++){
        let file = files[i]

        if (props.debug) console.log(file.type)
        let isType = props.accept=="*"?true:props.accept.some(t => t === file.type)
        let isLimit = file.size < props.maxsize

        if (!isType) {
            proxy.elMessageMixin(`${file.type}格式不正确`, 'error')
            return
        }
        if (!isLimit) {
            proxy.elMessageMixin(`${file.name}超过${props.maxsize/file.size}M`, 'error')
            return
        }

        //检查完成，可以上传
        const curItem = Math.random()
        let upItem = {
            id: curItem,
            name: file.name,
            progressFlag: true,
            loadProgress: 0,
            // fileUrl: "", //不给，到完成再给，这样上面就能判断了
            isImg: props.accept.includes('*')?'':imgTypes.some(p => p === file.name.split('.').pop().toLowerCase())
        }
        obj.fileurls.push(upItem) //加到前面
        let formData = new FormData(); //这样可以给form参数了
        formData.append("type", file.type);
        formData.append("file", file);
        if (props.maxwidth > 0) formData.append("maxheight", props.maxwidth);
        if (props.maxheight > 0) formData.append("maxwidth", props.maxheight);
        if (props.background != "") formData.append("background", props.background);

        const up=()=>{
            return new Promise((resovle,rej)=>{
                proxy.$ajax({
                    baseURL: "",
                    url: proxy.$setting.globalUrl.uploadserver,
                    data: formData,
                    isUploadFile: true,
                    bfLoading: false,
                    timeout: 0,
                    progress: p => {
                        obj.fileurls.find(t => t.id==curItem).loadProgress = (p.loaded / p.total * 100 | 0) //这里不能直接用upItem，因为实际上这时还没绑上去，即指向还未生效
                    }
                }).then(res => {
                    upItem.isUpload = true
                    upItem.fileUrl = res.filename
                    upItem.name = res.filename
                    upItem.progressFlag = false
                    proxy.useTrigger()
                    const updatefiles = (Array.from(obj.fileurls,({name})=>name)).join(',')
                    emit('update:files',updatefiles)
                    resovle(upItem)
                }).catch((() => {
                    upItem.progressFlag = false
                    resovle(upItem)
                }))
            })
        }
        await up()
    }
}

const PreviewFile=(fileUrl)=>{
    if(!fileUrl){
        return
    }
    let type = fileUrl.split(/\.(?=[^\.]+$)/)[1]
    if(['jpg','png','gif','jpeg'].includes(type)){
        obj.PreviewObj = {
            Visible: true,
            type: type,
            fileURL: fileUrl
        }
    }else{
        window.open(fileUrl,'_blank')
    }
}

const download=(fileUrl)=>{
    if(!fileUrl){
        return
    }
    window.open(fileUrl,'_blank')
}

let { fileurls } = toRefs(obj)
</script>

<style lang="scss" scoped>
    $w: 120px;
    $h: 120px;
    $color: #d8dae2;
    .ups {
         display: flex; flex-wrap: wrap; 

        .fileDiv { margin-right: 5px; margin-bottom: 5px; position: relative; }
        .upDiv { position: relative; width: $w; height: $h+20; overflow: hidden; }
        .up_del {
            position: absolute; top: 5px; right: 6px; font-size: 18px; color: $red-color; cursor: pointer;
            .down{font-size: 20px; color: $green-color;}
        }
        // .up_del::after { content: "\e74b"; font-family: "iconfont"; cursor: pointer; font-size: 16px;}
        .upDiv input { position: absolute; top:-20px; font-size:0; -webkit-appearance:none; width: $w; height: $h+20; }
        .avatar { width: $w; height: $h; object-fit: contain; box-sizing: border-box; border: 1px solid $color; }
        .avatar-uploader-file::after { content:'\e6b7'; font-family: "iconfont"; font-size: 40px; }
        .avatar-uploader-file span { position: absolute; bottom: 0; font-size: 12px; }
        .avatar-uploader,.avatar-uploader-file, .up_uploading { position: relative; width: $w; height: $h; overflow: hidden; background-color: #FFF; border: 1px solid $color; box-sizing: border-box; display: flex; justify-content: center; align-items: center; }
        .avatar-uploader::after { content:'\e626'; font-family: "iconfont"; font-size: 40px; color: $color; }
        .up_uploading { font-size:12px; }
        .progress { display: flex; width:120px; margin-top: 3px; align-items: center; }
        .progress * { display: flex; font-style: normal; font-size: 12px; }
        .progress span { flex: 1; align-items: center; height:6px; border-radius: 3px; background-color: $color; margin-right: 5px; }
        .progress u { background-color: #3a4fbd; height:6px; border-radius: 3px;  }

    }
    .lineups{
        .fileDivbox{
            display: flex; flex-direction: column; width: 100px;
            .fileDiv{
                position: relative;
                .up_del{
                    position: absolute; right: -15px; top: 0; cursor: pointer;
                }
                .up_del::after { content: "\e74b"; font-family: "iconfont"; font-size: 10px; }
            }
            .progressbox,.progress{
                display: flex; flex-direction: row; align-items: center;
            }
            
        }
        .lineupDiv{
            position: relative; height: 32px; overflow: hidden;
            .avatar-uploader{
                padding: 0 10px; height: 32px; border-radius: 5px; background: #409eff;font-size: 12px !important;
                display: flex; justify-content: center; align-items: center;
                color: #fff; cursor: pointer;
            }
            .avatar-uploader:hover{
                background: #72b9ff;
            }
            input{
                position: absolute; top:0px; font-size:0; -webkit-appearance:none; width: 100px; height: 32px;opacity: 0;
                cursor: pointer;
            }
        }
    }
    .pre-dialog{
        position: fixed; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5);
        display: flex; justify-content: center; align-items: center; z-index: 9999;
        .close-icon{
            position: absolute; right: 0; top: 0; z-index: 999989999999434; font-size: 28px; background: #606266; cursor: pointer;
            width: 44px; height: 44px; border-radius: 44px; line-height: 44px; text-align: center;
        }
    }
    iframe{
        border: none !important;
    }
    .nodata-a{color: #999;}
    .nodata-a:hover{color: #409eff;}
</style>